/*
 * Copyright (C) 2012-2016 Markus Junginger, greenrobot (http://greenrobot.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.greenrobot.eventbus.util;

import ohos.agp.window.dialog.BaseDialog;
import ohos.agp.window.dialog.PopupDialog;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import ohos.utils.PacMap;

import java.io.IOException;

import org.greenrobot.eventbus.Logger;

import java.util.logging.Level;

/**
 * Factory to allow injecting a more complex exception mapping; typically you would subclass one of {@link Honeycomb} or
 * {@link Support}.
 */
public abstract class ErrorDialogFragmentFactory<T> {

    /**
     * errorConfig
     */
    protected final ErrorDialogConfig config;


    protected ErrorDialogFragmentFactory(ErrorDialogConfig config) {
        this.config = config;
    }

    /**
     * Prepares the fragment's arguments and creates the fragment. May be overridden to provide custom error fragments.
     *
     * @param event                   failureEvent
     * @param finishAfterDialog       dialog
     * @param argumentsForErrorDialog errorDialog
     * @return T
     */
    protected T prepareErrorFragment(
            ThrowableFailureEvent event, boolean finishAfterDialog, PacMap argumentsForErrorDialog) {
        if (event.isSuppressErrorUi()) {
            // Show nothing by default
            return null;
        }
        PacMap bundle;
        if (argumentsForErrorDialog != null) {
            try {
                bundle = (PacMap) argumentsForErrorDialog.clone();
            } catch (CloneNotSupportedException e) {
                Logger.Default.get().log(Level.WARNING, e.toString());
                bundle = new PacMap();
            }
        } else {
            bundle = new PacMap();
        }

        if (!bundle.hasKey(ErrorDialogManager.KEY_TITLE)) {
            String title = getTitleFor(event, bundle);
            bundle.putString(ErrorDialogManager.KEY_TITLE, title);
        }
        if (!bundle.hasKey(ErrorDialogManager.KEY_MESSAGE)) {
            String message = getMessageFor(event, bundle);
            bundle.putString(ErrorDialogManager.KEY_MESSAGE, message);
        }
        if (!bundle.hasKey(ErrorDialogManager.KEY_FINISH_AFTER_DIALOG)) {
            bundle.putBooleanValue(ErrorDialogManager.KEY_FINISH_AFTER_DIALOG, finishAfterDialog);
        }
        if (!bundle.hasKey(ErrorDialogManager.KEY_EVENT_TYPE_ON_CLOSE)
                && config.defaultEventTypeOnDialogClosed != null) {
            bundle.putSerializableObject(ErrorDialogManager.KEY_EVENT_TYPE_ON_CLOSE, config.defaultEventTypeOnDialogClosed);
        }
        if (!bundle.hasKey(ErrorDialogManager.KEY_ICON_ID) && config.defaultDialogIconId != 0) {
            bundle.putIntValue(ErrorDialogManager.KEY_ICON_ID, config.defaultDialogIconId);
        }
        return createErrorFragment(event, bundle);
    }

    /**
     * Returns either a new Honeycomb+ or a new support library DialogFragment.
<<<<<<< Updated upstream
=======
     *
     * @param event     event
     * @param arguments arguments
     * @return T
>>>>>>> Stashed changes
     */
    protected abstract T createErrorFragment(ThrowableFailureEvent event, PacMap arguments);

    /**
     * May be overridden to provide custom error title.
<<<<<<< Updated upstream
=======
     * @param event event
     * @param arguments arguments
     * @return String
>>>>>>> Stashed changes
     */
    protected String getTitleFor(ThrowableFailureEvent event, PacMap arguments) {
        try {
            return config.resources.getElement(config.defaultTitleId).getString();
        } catch (IOException | NotExistException | WrongTypeException e) {
            Logger.Default.get().log(Level.WARNING, e.toString());
        }
        return null;
    }

    /**
     * May be overridden to provide custom error messages.
     * @param event event
     * @param arguments arguments
     * @return String
     */
    protected String getMessageFor(ThrowableFailureEvent event, PacMap arguments) {
        int msgResId = config.getMessageIdForThrowable(event.throwable);
        try {
            return config.resources.getElement(msgResId).getString();
        } catch (IOException | NotExistException | WrongTypeException e) {
            Logger.Default.get().log(Level.WARNING, e.toString());
        }
        return null;
    }


    /**
     * class to show error
     */
    public static class Support extends ErrorDialogFragmentFactory<BaseDialog> {
        public Support(ErrorDialogConfig config) {
            super(config);
        }

        /**
         * method to show error
         * @param event event
         * @param arguments arguments
         * @return BaseDialog
         */
        protected BaseDialog createErrorFragment(ThrowableFailureEvent event, PacMap arguments) {
            return new PopupDialog(null, null, 0, 0);
        }
    }
}
